package tx.os3.clientserver.client.model;

import java.util.Date;

import tx.os3.clientserver.client.model.FileRepresentation.FileType;

public final class FileRepresentationParser {

    private FileRepresentationParser() {

    }

    /**
     * Gets the {@link FileType} for the given file representation string.
     * 
     * @param fileRepresentationString
     * @return
     */
    public static FileType getFileType(String fileRepresentationString) {
        if(!isValid(fileRepresentationString)) {
            throw new IllegalArgumentException(
                    "File representation string is not valid.");
        }
        String typeString = fileRepresentationString.substring(0, 1);

        for(FileType type : FileType.values()) {
            if(type.toString().equals(typeString)) {
                return type;
            }
        }

        return null;
    }

    public static String getFileName(String fileRepresentationString) {
        if(!isValid(fileRepresentationString)) {
            throw new IllegalArgumentException(
                    "File representation string is not valid.");
        }

        String fileName = fileRepresentationString.substring(
                getFileType(fileRepresentationString).toString().length())
                .trim();

        // Strip first quote
        if(fileName.startsWith("\"")) {
            fileName = fileName.substring(1);
        }

        // Find and strip last quote
        for(int i = 0; i < fileName.length(); i++) {
            if(fileName.charAt(i) == '"') {
                fileName = fileName.substring(0, i);
                break;
            }
        }

        return fileName;

    }
    
    public static Date getLastModifiedDate(String fileRepresentationString) {
        if(!isValid(fileRepresentationString)) {
            throw new IllegalArgumentException(
                    "File representation string is not valid.");
        }

        String[] split = fileRepresentationString.split(" ");
        long milliseconds = Long.parseLong(split[split.length-1])*1000;

        return new Date(milliseconds);
    }

    public static boolean isValid(String fileRepresentationString) {
        if(fileRepresentationString == null) {
            throw new IllegalArgumentException("String cannot be null.");
        }
        boolean isValid = false;

        // Check for file type
        for(FileType type : FileType.values()) {
            isValid = fileRepresentationString.startsWith(type.toString());
            if(isValid) {
                break;
            }
        }

        return isValid;
    }

}
